<template>
  <div class="app-container">
    <!-- 数据统计卡片 -->
    <el-row :gutter="20" class="statistics-container">
      <el-col :span="6" v-for="(item, index) in orderStats" :key="index">
        <el-card shadow="hover" class="statistics-card">
          <template #header>
            <div class="card-header">
              <span>{{ item.title }}</span>
              <el-tag :type="item.tagType" effect="plain">{{ item.tag }}</el-tag>
            </div>
          </template>
          <div class="statistics-value">
            <div class="number-wrapper">
              <span class="number">{{ item.value }}</span>
              <span class="unit">{{ item.unit }}</span>
            </div>
            <div class="description-text">
              <el-icon><TrendCharts /></el-icon>
              <span>{{ item.description }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索栏 -->
    <el-card class="search-wrapper">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
        <el-form-item label="订单编号" prop="orderNo">
          <el-input
            v-model="queryParams.orderNo"
            placeholder="请输入订单编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="订单状态" clearable>
            <el-option
              v-for="dict in order_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="order-list">
      <el-table
        v-loading="loading"
        :data="orderList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="订单编号" align="center" prop="orderNo" />
        <el-table-column label="商品信息" align="center" prop="productInfo">
          <template #default="scope">
            <div class="product-info">
              <div class="product-detail">
                <div class="product-name">{{ scope.row.productName }}</div>
                <div class="product-spec">{{ scope.row.productSpec }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="订单金额" align="center" prop="totalAmount">
          <template #default="scope">
            ￥{{ scope.row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="支付方式" align="center" prop="payMethod" width="120">
          <template #default="scope">
            <dict-tag :options="pay_method" :value="scope.row.payMethod" />
          </template>
        </el-table-column>
        <el-table-column label="订单状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="order_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="下单时间" align="center" prop="createTime" width="180" />
        <el-table-column label="操作" align="center" width="420">
          <template #default="scope">
            <el-button
              type="primary"
              link
              icon="View"
              @click="handleViewDetail(scope.row)"
            >查看详情</el-button>
            <el-button
              v-if="scope.row.status === 1"
              type="success"
              link
              icon="Van"
              @click="handleDelivery(scope.row)"
            >发货</el-button>
            <el-button
              v-if="scope.row.status === 1"
              type="danger"
              link
              icon="Close"
              @click="handleCancel(scope.row)"
            >取消</el-button>
            <el-button
              type="warning"
              link
              icon="Edit"
              @click="handleRemark(scope.row)"
            >备注</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      v-model="dialogVisible"
      width="800px"
      append-to-body
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单编号">{{ orderDetail.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ orderDetail.createTime }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <dict-tag :options="order_status" :value="orderDetail.status" />
        </el-descriptions-item>
        <el-descriptions-item label="支付方式">
          <dict-tag :options="pay_method" :value="orderDetail.payMethod" />
        </el-descriptions-item>
        <el-descriptions-item label="支付时间">{{ orderDetail.payTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="发货时间">{{ orderDetail.deliveryTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="收货人">{{ orderDetail.receiverName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ orderDetail.receiverPhone }}</el-descriptions-item>
        <el-descriptions-item label="收货地址" :span="2">{{ orderDetail.receiverAddress }}</el-descriptions-item>
        <el-descriptions-item label="订单备注" :span="2">{{ orderDetail.remark || '-' }}</el-descriptions-item>
      </el-descriptions>

      <el-table :data="orderDetail.items" style="margin-top: 20px;">
        <el-table-column label="商品图片" align="center" width="100">
          <template #default="scope">
            <el-image
              :src="scope.row.productImage"
              :preview-src-list="[scope.row.productImage]"
              class="product-image-small"
            />
          </template>
        </el-table-column>
        <el-table-column label="商品名称" prop="productName" />
        <el-table-column label="规格" prop="specifications" width="120" />
        <el-table-column label="单价" prop="price" width="100">
          <template #default="scope">
            ￥{{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="数量" prop="quantity" width="80" align="center" />
        <el-table-column label="小计" width="120" align="right">
          <template #default="scope">
            ￥{{ scope.row.totalPrice.toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>

      <div class="order-summary">
        <div class="summary-item">
          <span>商品总额：</span>
          <span class="amount">￥{{ orderDetail.totalPrice?.toFixed(2) }}</span>
        </div>
        <div class="summary-item">
          <span>运费：</span>
          <span class="amount">￥{{ orderDetail.shippingFee?.toFixed(2) }}</span>
        </div>
        <div class="summary-item">
          <span>优惠金额：</span>
          <span class="amount">-￥{{ orderDetail.discount?.toFixed(2) }}</span>
        </div>
        <div class="summary-item total">
          <span>实付金额：</span>
          <span class="amount">￥{{ (orderDetail.totalPrice + orderDetail.shippingFee - orderDetail.discount)?.toFixed(2) }}</span>
        </div>
      </div>
    </el-dialog>

    <!-- 发货对话框 -->
    <el-dialog
      title="订单发货"
      v-model="deliveryDialog"
      width="500px"
      append-to-body
    >
      <el-form ref="deliveryFormRef" :model="deliveryForm" :rules="deliveryRules" label-width="100px">
        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="deliveryForm.orderNo" disabled />
        </el-form-item>
        <el-form-item label="快递公司" prop="expressCompany">
          <el-select v-model="deliveryForm.expressCompany" placeholder="请选择快递公司">
            <el-option label="顺丰快递" value="顺丰快递" />
            <el-option label="中通快递" value="中通快递" />
            <el-option label="圆通快递" value="圆通快递" />
            <el-option label="韵达快递" value="韵达快递" />
            <el-option label="申通快递" value="申通快递" />
          </el-select>
        </el-form-item>
        <el-form-item label="快递单号" prop="expressNo">
          <el-input v-model="deliveryForm.expressNo" placeholder="请输入快递单号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deliveryDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitDelivery">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 取消订单对话框 -->
    <el-dialog
      title="取消订单"
      v-model="cancelDialog"
      width="500px"
      append-to-body
    >
      <el-form ref="cancelFormRef" :model="cancelForm" :rules="cancelRules" label-width="100px">
        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="cancelForm.orderNo" disabled />
        </el-form-item>
        <el-form-item label="取消原因" prop="cancelReason">
          <el-input
            v-model="cancelForm.cancelReason"
            type="textarea"
            placeholder="请输入取消原因"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitCancel">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改备注对话框 -->
    <el-dialog
      title="修改备注"
      v-model="remarkDialog"
      width="500px"
      append-to-body
    >
      <el-form ref="remarkFormRef" :model="remarkForm" :rules="remarkRules" label-width="100px">
        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="remarkForm.orderNo" disabled />
        </el-form-item>
        <el-form-item label="订单备注" prop="remark">
          <el-input
            v-model="remarkForm.remark"
            type="textarea"
            placeholder="请输入订单备注"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="remarkDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitRemark">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { listOrders, getOrder, getOrderStats, deliveryOrder, cancelOrder, updateOrderRemark } from '@/api/merchant/order'
import { ElMessage } from 'element-plus'

// 遮罩层
const loading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 订单表格数据
const orderList = ref([])
// 弹出层标题
const title = ref("")
// 是否显示弹出层
const dialogVisible = ref(false)
// 日期范围
const dateRange = ref([])
// 订单详情数据
const orderDetail = ref({})

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  orderNo: undefined,
  status: undefined,
  startTime: undefined,
  endTime: undefined
})

// 订单状态字典
const order_status = [
  { value: 0, label: "待付款", elTagType: "warning" },
  { value: 1, label: "待发货", elTagType: "info" },
  { value: 2, label: "待收货", elTagType: "success" },
  { value: 3, label: "已完成", elTagType: "" },
  { value: 4, label: "已取消", elTagType: "danger" }
]

// 支付方式字典
const pay_method = [
  { value: 1, label: "微信支付", elTagType: "success" },
  { value: 2, label: "支付宝支付", elTagType: "primary" }
]

// 统计数据
const orderStats = ref([
  { title: '今日订单', value: 0, unit: '单', tag: '实时', tagType: 'success', description: '较昨日增长10%' },
  { title: '待发货', value: 0, unit: '单', tag: '待处理', tagType: 'warning', description: '需要及时处理' },
  { title: '本月销售额', value: 0, unit: '元', tag: '月度', tagType: 'primary', description: '完成月度目标的85%' },
  { title: '订单完成率', value: 0, unit: '%', tag: '统计', tagType: 'info', description: '高于平均水平' }
])

// 发货对话框
const deliveryDialog = ref(false)
const deliveryFormRef = ref()
const deliveryForm = ref({
  orderNo: '',
  expressCompany: '',
  expressNo: ''
})
const deliveryRules = {
  expressCompany: [{ required: true, message: '请选择快递公司', trigger: 'change' }],
  expressNo: [{ required: true, message: '请输入快递单号', trigger: 'blur' }]
}

// 取消订单对话框
const cancelDialog = ref(false)
const cancelFormRef = ref()
const cancelForm = ref({
  orderNo: '',
  cancelReason: ''
})
const cancelRules = {
  cancelReason: [{ required: true, message: '请输入取消原因', trigger: 'blur' }]
}

// 备注对话框
const remarkDialog = ref(false)
const remarkFormRef = ref()
const remarkForm = ref({
  orderNo: '',
  remark: ''
})
const remarkRules = {
  remark: [{ required: true, message: '请输入订单备注', trigger: 'blur' }]
}

/** 查询订单列表 */
function getList() {
  loading.value = true
  // 处理时间范围
  const params = {
    ...queryParams.value,
    startTime: dateRange.value ? dateRange.value[0] : undefined,
    endTime: dateRange.value ? dateRange.value[1] : undefined
  }
  listOrders(params).then(response => {
    if (response.code === 200) {
      orderList.value = response.rows.map(order => ({
        ...order,
        totalAmount: order.totalPrice, // 适配前端显示
        productImage: order.items[0]?.productImage || '', // 取第一个商品的图片
        productName: order.items[0]?.productName || '',
        productSpec: order.items[0]?.specifications || ''
      }))
      total.value = response.total
    } else {
      ElMessage.error(response.msg)
    }
    loading.value = false
  })
}

/** 查询订单统计 */
function getStats() {
  getOrderStats().then(response => {
    // 更新统计数据
    orderStats.value[0].value = response.todayOrders
    orderStats.value[1].value = response.pendingShipments
    orderStats.value[2].value = response.monthSales
    orderStats.value[3].value = response.completionRate
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    orderNo: undefined,
    status: undefined,
    startTime: undefined,
    endTime: undefined
  }
  handleQuery()
}

/** 查看订单详情 */
function handleViewDetail(row) {
  getOrder(row.orderNo).then(response => {
    orderDetail.value = response.data
    dialogVisible.value = true
  })
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.orderId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 发货按钮操作 */
function handleDelivery(row) {
  deliveryForm.value = {
    orderNo: row.orderNo,
    expressCompany: '',
    expressNo: ''
  }
  deliveryDialog.value = true
}

/** 提交发货 */
function submitDelivery() {
  deliveryFormRef.value.validate(valid => {
    if (valid) {
      deliveryOrder(deliveryForm.value).then(response => {
        if (response.code === 200) {
          ElMessage.success('发货成功')
          deliveryDialog.value = false
          getList()
        } else {
          ElMessage.error(response.msg)
        }
      })
    }
  })
}

/** 取消订单按钮操作 */
function handleCancel(row) {
  cancelForm.value = {
    orderNo: row.orderNo,
    cancelReason: ''
  }
  cancelDialog.value = true
}

/** 提交取消订单 */
function submitCancel() {
  cancelFormRef.value.validate(valid => {
    if (valid) {
      cancelOrder(cancelForm.value).then(response => {
        if (response.code === 200) {
          ElMessage.success('取消订单成功')
          cancelDialog.value = false
          getList()
        } else {
          ElMessage.error(response.msg)
        }
      })
    }
  })
}

/** 修改备注按钮操作 */
function handleRemark(row) {
  remarkForm.value = {
    orderNo: row.orderNo,
    remark: row.remark || ''
  }
  remarkDialog.value = true
}

/** 提交备注 */
function submitRemark() {
  remarkFormRef.value.validate(valid => {
    if (valid) {
      updateOrderRemark(remarkForm.value).then(response => {
        if (response.code === 200) {
          ElMessage.success('修改备注成功')
          remarkDialog.value = false
          getList()
        } else {
          ElMessage.error(response.msg)
        }
      })
    }
  })
}

onMounted(() => {
  getList()
  getStats()
})
</script>

<style scoped>
.statistics-container {
  margin-bottom: 20px;
}

.statistics-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .statistics-value {
    .number-wrapper {
      margin: 10px 0;
      
      .number {
        font-size: 24px;
        font-weight: bold;
        margin-right: 5px;
      }
      
      .unit {
        font-size: 14px;
        color: #666;
      }
    }

    .description-text {
      font-size: 12px;
      color: #666;
      display: flex;
      align-items: center;
      gap: 5px;
    }
  }
}

.search-wrapper {
  margin-bottom: 20px;
}

.product-info {
  display: flex;
  align-items: center;
  
  .product-image {
    width: 50px;
    height: 50px;
    margin-right: 10px;
  }

  .product-detail {
    text-align: left;
    
    .product-name {
      font-weight: bold;
      margin-bottom: 5px;
    }
    
    .product-spec {
      font-size: 12px;
      color: #666;
    }
  }
}

.product-image-small {
  width: 40px;
  height: 40px;
}

.order-summary {
  margin-top: 20px;
  border-top: 1px solid #EBEEF5;
  padding-top: 20px;

  .summary-item {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-bottom: 10px;
    font-size: 14px;

    &.total {
      font-size: 16px;
      font-weight: bold;
      border-top: 1px solid #EBEEF5;
      padding-top: 10px;
      margin-top: 10px;
    }

    .amount {
      min-width: 100px;
      text-align: right;
      color: #606266;

      &.red {
        color: #f56c6c;
      }
    }
  }
}
</style> 